
package com.scs.application.modules.base.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.model.RestResult;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.core.utils.BeanValidators;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.base.entity.HospitalMaterial;
import com.scs.application.modules.base.entity.HospitalSupplier;
import com.scs.application.modules.base.entity.MaterialSpec;
import com.scs.application.modules.base.mapper.MaterialSpecMapper;
import com.scs.application.modules.base.request.HospitalSupplierQueryRequest;
import com.scs.application.modules.base.request.MaterialSpecQueryRequest;
import com.scs.application.modules.base.service.HospitalMaterialService;
import com.scs.application.modules.base.service.MaterialSpecService;
import com.scs.application.modules.design.service.QueryGenerator;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品规格 controller
 */
@AllArgsConstructor
@RestController
@RequestMapping("/base/material_specs")
public class MaterialSpecController extends CrudController<MaterialSpec, String, MaterialSpecService> implements ImAndExAbleController<MaterialSpecQueryRequest> {

    @Autowired
    private HospitalMaterialService hospitalMaterialService;

    @Autowired
    private MaterialSpecMapper materialSpecMapper;

    @GetMapping("/page")
    public PageResult page(MaterialSpecQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @GetMapping("/list")
    public CommonResult list(MaterialSpecQueryRequest request) {
        List<MaterialSpec> list = service.list(request);
        return CommonResult.ok("查询成功", list);
    }

    @PutMapping("/batch_save")
    public CommonResult batchSave(@RequestBody List<MaterialSpec> children) {
        Assert.notEmpty(children, "至少有一条商品规格");
        BeanValidators.validateListWithException(validator, children);

        for(MaterialSpec materialSpec : children) {
            if (StringUtils.isEmpty(materialSpec.getHospitalId())) {
                materialSpec.setCertificateNo(materialSpec.getHospitalCertificateNo())
                        .setCertificateExpiredDate(materialSpec.getHospitalCertificateExpiredDate())
                        .setCertificateExpiredStartDate(materialSpec.getHospitalCertificateExpiredStartDate());
            } else { //更新关联医院耗材信息
                hospitalMaterialService.update(Wrappers.<HospitalMaterial>update()
                        .set("certificate_no", materialSpec.getHospitalCertificateNo())
                        .set("certificate_expired_date", materialSpec.getHospitalCertificateExpiredDate())
                        .set("certificate_expired_start_date", materialSpec.getHospitalCertificateExpiredStartDate())
                        .set("hospital_catalog_id", materialSpec.getHospitalCatalogId())
                        .set("is_sun_purchase", StringUtils.isBlank(materialSpec.getSunPurchaseCode()) ? 0 : 1)
                        .set("sun_purchase_code", materialSpec.getSunPurchaseCode())
                        .set("medical_consumables_code", materialSpec.getMedicalConsumablesCode())
                        .eq("material_code", materialSpec.getMaterialCode())
                        .eq("material_spec_id", materialSpec.getId())
                        .eq("supplier_id", materialSpec.getSupplierId())
                        .eq("hospital_id", materialSpec.getHospitalId()));
            }
        }
        boolean bSuccess = service.saveOrUpdateBatch(children);
        return bSuccess ? CommonResult.ok("保存成功") : CommonResult.error("保存失败");
    }

    @Override
    @PutMapping
    public CommonResult update(@RequestBody @Valid MaterialSpec entity) {
        if (StringUtils.isEmpty(entity.getHospitalId())) {
//            entity.setCertificateNo(entity.getHospitalCertificateNo())
//                    .setCertificateExpiredDate(entity.getHospitalCertificateExpiredDate())
//                    .setCertificateExpiredStartDate(entity.getHospitalCertificateExpiredStartDate());
        } else { //更新关联医院耗材信息
            hospitalMaterialService.update(Wrappers.<HospitalMaterial>update()
//                    .set("certificate_no", entity.getHospitalCertificateNo())
//                    .set("certificate_expired_date", entity.getHospitalCertificateExpiredDate())
//                    .set("certificate_expired_start_date", entity.getHospitalCertificateExpiredStartDate())
                    .set("hospital_catalog_id", entity.getHospitalCatalogId())
                    .set("is_sun_purchase", StringUtils.isBlank(entity.getSunPurchaseCode()) ? 0 : 1)
                    .set("sun_purchase_code", entity.getSunPurchaseCode())
                    .set("medical_consumables_code", entity.getMedicalConsumablesCode())
                    .eq("material_code", entity.getMaterialCode())
                    .eq("material_spec_id", entity.getId())
                    .eq("supplier_id", entity.getSupplierId())
                    .eq("hospital_id", entity.getHospitalId()));
        }
        return  super.update(entity);
    }

    @Override
    @PostMapping
    public CommonResult add(@RequestBody @Valid MaterialSpec entity) {
        entity.setCertificateNo(entity.getHospitalCertificateNo())
                .setCertificateExpiredDate(entity.getHospitalCertificateExpiredDate())
                .setCertificateExpiredStartDate(entity.getHospitalCertificateExpiredStartDate());
        return super.add(entity);
    }


    /***
     * @param entity
     * @Description:  通用保存、更新
     */
    @PostMapping("/saveOrUpdateCommon")
    public RestResult saveOrUpdateCommon(@Valid @RequestBody MaterialSpec entity) {
        if (entity.isNewRecord()) {
            this.add(entity);
        } else{
            this.update(entity);
        }
        return RestResult.ok("操作成功", entity);
    }


    /***
     * @date: 2024/6/24
     * @Description:  添加数据过滤条件
     */
    @Override
    public void fillQueryAuth(QueryWrapper queryWrapper,MaterialSpec entity) {
        if (UserUtils.isAdmin()) {
            return;
        }
        // 医院
        if (UserUtils.isHospital())  {
            HospitalSupplierQueryRequest hospitalSupplierQueryRequest = new HospitalSupplierQueryRequest();
            hospitalSupplierQueryRequest.setHospitalId(UserUtils.getHospitalId());
            List<HospitalSupplier> hospitalSupplierList = hospitalSupplierService.list(hospitalSupplierQueryRequest);
            if (!hospitalSupplierList.isEmpty()) {
                List<String> supIdList = hospitalSupplierList.stream().map(HospitalSupplier::getSupplierId).distinct().collect(Collectors.toList());
                queryWrapper.in("supplier_id", supIdList);
            } else {
                queryWrapper.eq("supplier_id", "-1");
            }
        }
        // 供应商
        if (UserUtils.isSupplier())  {
            queryWrapper.eq("supplier_id", UserUtils.getSupplierId());
        }
    }

    /***
     * @param request
     * @Description:  商品供货资格添加时使用
     */
    @GetMapping("/pageForMaterialApplicantAdd")
    public PageResult pageForMaterialApplicantAdd(HttpServletRequest request,@RequestParam Map<String, String> reqData) {
        IPage<MaterialSpec> page = QueryGenerator.parsePage(request);
        QueryWrapper<MaterialSpec> queryWrapper = QueryGenerator.initQueryWrapper(request);
        String supplierId = null;
        String hospitalId = null;
        if (reqData.containsKey("userParam")) {
            JSONObject ob = JSON.parseObject(reqData.get("userParam") + "");
            supplierId = ob.getString("supplierId");
            hospitalId = ob.getString("hospitalId");
        }
        BusinessException.throwErrorIf(StringUtils.isBlank(hospitalId), "查询失败，缺少参数hospitalId");
        BusinessException.throwErrorIf(StringUtils.isBlank(supplierId), "查询失败，缺少参数supplierId");

        IPage pageResult = materialSpecMapper.pageForMaterialApplicantAdd(page, queryWrapper,supplierId,hospitalId);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }
}
